package com.fmh.mybatisplus.controller;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fmh.mybatisplus.comoon.dto.MenuDto;
import com.fmh.mybatisplus.comoon.vo.Result;
import com.fmh.mybatisplus.pojo.Menu;
import com.fmh.mybatisplus.pojo.User;
import com.fmh.mybatisplus.service.MenuService;
import com.fmh.mybatisplus.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.List;

@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;
    @Autowired
    private UserService userService;


    @GetMapping("/nav")
    public Result nav(Principal principal) {

        // 获取当前登录用户信息
        User user = userService.getByUserName(principal.getName());

        // 获取权限信息
        String authorityInfo = userService.getUserAuthorityInfo(user.getId());

        // 转换成数组
        String[] tokenizeToStringArray = StringUtils.tokenizeToStringArray(authorityInfo, ",");

        // 获取导航栏信息
        List<MenuDto> navs = menuService.getCurrentUserNav();

        return Result.success(MapUtil.builder()
                .put("authoritys", tokenizeToStringArray)
                .put("menus", navs)
                .map()
        );
    }


    @GetMapping("/info/{id}")
    public Result info(@PathVariable Long id) {
        Menu byId = menuService.getById(id);
        return Result.success(byId);
    }

    @GetMapping("/list")
    public Result list() {
        List<Menu> tree = menuService.tree();
        return Result.success(tree);
    }

    @PostMapping("/save")
    public Result save(@Validated @RequestBody Menu menu) {
        menuService.save(menu);
        return Result.success(menu);
    }

    @PostMapping("/update")
    public Result update(@Validated @RequestBody Menu menu) {
        menuService.updateById(menu);
        return Result.success(menu);
    }

    @PostMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Long id) {

        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);

        long count = menuService.count(wrapper);

        if (count > 0) {
            return Result.error("请先删除子菜单");
        }

        menuService.removeById(id);

        return Result.success("");
    }
}
